using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Urls;

namespace Medianamik.UI.Controls
{
    public class DiffLink : HyperLink
    {
        private static string DIFF_PAGE = "/medianamik/contentmanagement/previewFrame.aspx";
        private const string ENABLED_IMAGE_URL = "/Medianamik/images/Icones/Ico_Visualisation.gif";
        private const string DISABLED_IMAGE_URL = "/Medianamik/images/Icones/Ico_VisualisationInactif.gif";

        private Image _image = new Image();

        public Guid NodeId
        {
            get
            {
                return ViewState["NodeId"] as Guid?
                       ?? Guid.Empty;
            }
            set
            {
                ViewState["NodeId"] = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.PreRender += DiffLink_PreRender;
        }

        void DiffLink_PreRender(object sender, EventArgs e)
        {
            var dico = new ObjectFactory<IUrlDictionary>().Get();
            var entries = dico.GetEntries(NodeId, MedianamikContext.Current.EditionCulture);
            var url = entries.FirstOrDefault(u => Page.Request.Url.Authority.EqualsIgnoreCase(u.Domain));
            if (url == null)
            {
                url = entries.FirstOrDefault();
            }
            if (url != null)
            {
                NavigateUrl = DIFF_PAGE + "?url=" + Page.Server.UrlEncode(url.RequestedUrl.ToString());
            }

            if (url == null || !Enabled)
            {
                _image.ImageUrl = DISABLED_IMAGE_URL;
            }
            else
            {
                _image.ImageUrl = ENABLED_IMAGE_URL;
            }

            this.Target = "_blank";

        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Controls.Add(_image);
        }

    }
}
